<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect v-model="form.model_id" placeholder="系统模块" :options="options.model_id" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.reason_type" placeholder="原因类型" :options="options.reason_type" multiple collapse-tags style="min-width: 160px" />
        <el-input v-model="form.name" placeholder="原因名称" class="w-40" />
        <VSelect v-model="form.status" placeholder="状态" :options="options.status" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.create_user_id" placeholder="创建人" multiple collapse-tags filterable clearable style="min-width: 160px" />
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/settings/reason/add" type="primary" @click="handleRow('add')"><i class="dk-iconfont icon-Plus" />添加
        </VButton>
        <VButton auth="/purchase/settings/reason/status" :loading="loadings.start" @click="handleBatch('start')">
          <VStatus :value="true" />
        </VButton>
        <VButton auth="/purchase/settings/reason/status" :loading="loadings.stop" @click="handleBatch('stop')">
          <VStatus :value="false" />
        </VButton>
        <VButton auth="/purchase/settings/reason/priority" @click="handleBatch('priority')">调整优先级
        </VButton>
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <Priority ref="priorityRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Priority from './components/Priority'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox, ElSwitch } from 'element-plus'

const baseName = 'reason_config'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const priorityRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const rc_ids = selection.map(d => d.rc_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    start: () => {
      showLoading()
      api.status({ rc_ids, status: 1 }).then(res => {
        query()
        ElMessage({ type: 'success', message: '操作成功!' })
      }).finally(closeLoading)
    },
    stop: () => {
      showLoading()
      api.status({ rc_ids, status: 2 }).then(res => {
        query()
        ElMessage({ type: 'success', message: '操作成功!' })
      }).finally(closeLoading)
    },
    priority: () => {
      const {model_ids, reason_types} = selection.reduce((acc, cur) => {
        acc.model_ids.push(cur.model_id)
        acc.reason_types.push(cur.reason_type)
        return acc
      },{model_ids: [], reason_types: []})
      if([...new Set(model_ids)].length > 1 || [...new Set(reason_types)].length > 1) {
        ElMessage.error('只能勾选单个系统模块的单一原因类型调整优先级')
        return
      }
      priorityRef?.value.open(selection)
    }
  }
  handle[name]()
}

// 单行操作
const addRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { rc_id } = row || {}
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    add: () => {
      addRef?.value.open()
    },
    edit: () => {
      addRef?.value.open(rc_id)
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, rc_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    data: {
      dateRange: { type: 'update_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    { title: '系统模块', field: 'model_id_name'},
    { title: '原因类型', field: 'reason_type_name'},
    { title: '原因名称', field: 'name'},
    { title: '添加人', field: 'create_user'},
    { title: '添加时间', field: 'update_time'},
    { title: '优先级', field: 'level', width: 80},
    {
      title: '状态', field: 'status_name', width: 100, slots: {
        default: ({ row }) => <VStatus value={row.status_name === '启用'} />
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return <div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/settings/reason/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton>
            <VButton auth="/purchase/settings/reason/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>